package com.example.lightenergypolymerize.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.lightenergypolymerize.entity.Answer;
import com.example.lightenergypolymerize.entity.enums.AiModelEnum;
import com.example.lightenergypolymerize.entity.enums.AiTypeEnum;
import com.example.lightenergypolymerize.service.IAnswerService;
import com.example.lightenergypolymerize.util.AppVariable;
import com.example.lightenergypolymerize.util.ResponseEntity;
import com.example.lightenergypolymerize.util.SecurityUtil;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/doubao")
public class DouBaoController {
    @Value("${zijie.api-key}")
    private String apiKey;
    @Value("${zijie.url}")
    private String url;
    @Value("${zijie.model-id}")
    private String modelId;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @RequestMapping("/chat")
    public ResponseEntity chat(String question){
        if(!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }

        String result = "";//大模型返回的结果
        boolean addResult = false;//数据是否添加到了数据库
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        //1.获取分布式锁示例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            //2.获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                //获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口");
            }
            //1.api-key,调用url地址
            ArkService service = ArkService.builder().apiKey(apiKey)
                    .baseUrl(url).build();
            //2.构建问题对象
            List<ChatMessage> messages = new ArrayList<>();
            messages.add(ChatMessage.builder()
                    .role(ChatMessageRole.USER)
                    .content(question)
                    .build());
            //3.创建对象进行对话
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model(modelId)
                    .messages(messages)
                    .build();
            //4.得到对话结果
            result = service.createChatCompletion(request)
                    .getChoices()
                    .get(0)
                    .getMessage()
                    .getContent().toString();
            //将对话信息存储到数据库
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.DOUBAO.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            addResult = answerService.save(answer);
        }catch (Exception e) {
        }finally {
            //3.释放分布式锁
            rLock.unlock();
        }
        if(addResult) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("数据保存失败，请重试！");
    }



    @PostMapping("/chatlist")
    public ResponseEntity chatList() {
        List<Answer> list = answerService.list(Wrappers.lambdaQuery(Answer.class)
                .eq(Answer::getUid, SecurityUtil.getCurrentUser().getUid())
                .eq(Answer::getModel, AiModelEnum.DOUBAO.getValue())
                .eq(Answer::getType, AiTypeEnum.CHAT.getValue())
                .orderByDesc(Answer::getAid)
        );
        return ResponseEntity.succ(list);
    }
}